import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as qiniu from 'qiniu';

@Injectable()
export class QiniuService {
  constructor(private readonly configService: ConfigService){}

  private readonly accessKey: string = this.configService.get('qiniu.accessKey');
  private readonly secretKey: string = this.configService.get('qiniu.secretKey');
  private readonly bucket: string = this.configService.get('qiniu.bucket');

  private readonly mac = new qiniu.auth.digest.Mac(this.accessKey, this.secretKey);
  private readonly options = {
    scope: this.bucket,
  };

  private readonly uploadToken = new qiniu.rs.PutPolicy(this.options).uploadToken(this.mac);

  test(){
    return {
        accessKey : this.accessKey,
        secretKey : this.secretKey,
        bucket : this.bucket
    };
  }

  async uploadFile(file: Express.Multer.File): Promise<string> {
    const config = new qiniu.conf.Config();
    const formUploader = new qiniu.form_up.FormUploader(config);
    const putExtra = new qiniu.form_up.PutExtra();

    return new Promise((resolve, reject) => {
      formUploader.putFile(this.uploadToken,this.configService.get('qiniu.url','app/'),file.destination, null, (err, body, info) => {
        if (err) {
          reject(err);
        } else {
          if (info.statusCode === 200) {
            // 上传成功，返回七牛云中的图片链接
            resolve(`${this.configService.get('qiniu.url')}/${body.key}`);
          } else {
            reject(`Failed to upload. StatusCode: ${info.statusCode}`);
          }
        }
      });
    });
  }
}
